package com.siashan.toolkit.sms.chinamobile.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.siashan.toolkit.sms.core.exception.Unisms4jException;
import lombok.Data;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;

/**
 * 移动云短信请求类
 *
 * @author siashan
 * @since v1.0.1
 **/
@Data
public class ChinaMobileRequest {


    /**
     * 参数校验序列
     */
    private String mac;

    /**
     * 模版id
     */
    private String templateId;

    /**
     * 签名编码
     */
    private String sign;

    /**
     * 默认空字符串
     */
    private String addSerial = "";

    /**
     * 接收手机号
     */
    private String mobiles;

    /**
     * 参数列表
     */
    private String params;

    /**
     * 接口账户用户名
     */
    private String apId;

    /**
     * 企业名称
     */
    private String ecName;

    /**
     * 接口账号密码
     */
    private String secretKey;

    /**
     * 生成请求体body
     *
     * @return Body
     */
    public String genEncodeBody() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String reqText = objectMapper.writeValueAsString(this);
            //加密
            return Base64.encodeBase64String(reqText.getBytes());
        } catch (JsonProcessingException e) {
            throw new Unisms4jException("[移动云短信]发送失败", e);
        }
    }


    /**
     * 生成Mac
     *
     * @return Mac
     */
    public String genMac() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(this.getEcName());
        stringBuffer.append(this.getApId());
        stringBuffer.append(this.getSecretKey());
        stringBuffer.append(this.getTemplateId());
        stringBuffer.append(this.getMobiles());
        stringBuffer.append(this.getParams());
        stringBuffer.append(this.getSign());
        stringBuffer.append(this.getAddSerial());
        return Hex.encodeHexString(stringBuffer.toString().getBytes(StandardCharsets.UTF_8));
    }
}
